package com.jzoffer;

public class KthNode {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        ListNode l2 = new ListNode(5);
        ListNode l3 = new ListNode(49);
        ListNode l4 = new ListNode(79);
        ListNode l5 = new ListNode(3249);

        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;

        ListNode res = FindKthToTail(l1,4);
        System.out.println(res.val);

    }

    public static ListNode FindKthToTail(ListNode head,int k){
        if(head == null && k <= 0 ){
            return null;
        }
        ListNode p1 = head;
        while (p1 != null && k-- > 0){
            p1 = p1.next;
        }
        if(k > 0){
            return null;
        }
        ListNode p2 = head;
        while (p1 != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        return p2;

    }
}


